package framework.service;

import org.apache.log4j.Logger;

import common.LogCategory;

import framework.Trait;
import framework.Service;

/**
 * Implements the Service interface
 *
 * @author      Orlin Tomov
 * @version     0.2
 *
 */
public abstract class AbstractService extends Thread implements Service {

	protected static final Logger log = LogCategory.getCategory(AbstractService.class);
	/** the running status */
	private boolean running;
	/** the framework container where the service is deployed */
	private Trait container;

	/**
	 * @param	container
	 * @param	serviceName	of the service
	 */
	public AbstractService(Trait container, String serviceName) {
		this.container = container;
		this.setName(serviceName);
	}

	protected Trait getContainer() {
		return container;
	}

	/**
	 * Returns the info of the service. 
	 *
	 * @return	service info
	 */
	@Override
	public String info() {
		String result = getServiceName() + "\n";
		if (running) {
			result += "running\n";
		} else {
			result += "stoped\n";
		}
		return result;
	}

	/**
	 * Returns running status
	 *
	 * @return	running status of the service
	 * @see	#starting()
	 * @see	#stoping()
	 */
	@Override
	public boolean isRunning() {
		return running;
	}

	/**
	 * Returns the name of the service. 
	 *
	 * @return	service name
	 */
	@Override
	public String getServiceName() {
		return getName();
	}

	protected void setServiceName(String serviceName) {
		setName(serviceName);
	}

	/**
	 * Starts the service
	 *
	 * @see	#isRunning()
	 * @see	#stoping()
	 */
	@Override
	public void starting() {
		running = true;
		/**/log.info(getServiceName() + " is running ");
		if (!isAlive()) {
			start();
		}
	}

	/**
	 * Stops the service
	 *
	 * @see	#isRunning()
	 * @see	#starting()
	 */
	@Override
	public void stoping() {
		running = false;
		/**/log.info(getServiceName() + " is stopping ");
	}
}
